﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace BingWallpaper
{
	static class Program
	{
		private const int _imageWidth = 1920;
		private const int _imageHeight = 1200;

		// ReSharper disable InconsistentNaming
		private const int SPI_SETDESKWALLPAPER = 20;
		private const int SPIF_UPDATEINIFILE = 0x01;
		private const int SPIF_SENDWININICHANGE = 0x02;
		// ReSharper restore InconsistentNaming

		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		private static extern bool SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

		private static int GetWAHeight()
		{
			var wa = Screen.PrimaryScreen.WorkingArea;
			var waAspect = wa.Width/(double) wa.Height;
			var projected = _imageWidth/waAspect;
			return projected < _imageHeight ? (int)Math.Round(projected) : _imageHeight;
		}

		static void Main()
		{
			var imageInfo = BingWallpaperHelper.LoadImageInfo();
			if (imageInfo == null)
			{
				Console.WriteLine("No images available");
				return;
			}
			Console.WriteLine("Found image - " + imageInfo.Description);
			var fileName =
				Path.Combine(
					Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
					"bingwallpaper.bmp");

			var image = new Bitmap(BingWallpaperHelper.LoadImage(imageInfo.URIBase, 1920, 1200));
			const int border = 16;
			using (var g = Graphics.FromImage(image))
			{
				g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
				var font = new Font("Tahoma", 15);
				var textBounds = g.MeasureString(imageInfo.Description, font);
				var textPos = new PointF(image.Width - border - textBounds.Width, GetWAHeight() - border - textBounds.Height);
				g.DrawString(
					imageInfo.Description,
					font,
					Brushes.Black,
					textPos.X + 2,
					textPos.Y + 2);
				g.DrawString(
					imageInfo.Description,
					font,
					Brushes.White,
					textPos);
			}
			image.Save(fileName, ImageFormat.Bmp);

			if (File.Exists(fileName))
				Console.WriteLine("Image created - {0} bytes", new FileInfo(fileName).Length);

			if (SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, fileName, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE))
				Console.WriteLine("Desktop wallpaper set successfully");
			else
				throw new Win32Exception();
		}
	}
}
